package cn.felord.verse.configure;

import cn.felord.security.autoconfigure.PermissionService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * The type Spring mvc configuration.
 *
 * @author n1
 * @since 2021 /4/21 18:34
 */
@Configuration(proxyBeanMethods = false)
public class SpringMvcConfiguration implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 解决 String 统一封装RestBody的问题
        HttpMessageConverter<?> httpMessageConverter = converters.get(7);
        if (!(httpMessageConverter instanceof MappingJackson2HttpMessageConverter)) {
            throw new RuntimeException("MappingJackson2HttpMessageConverter is not here");
        }
        converters.add(0, httpMessageConverter);
    }

    @Bean
    UserDetailsService userDetailsService(){
        return new InMemoryUserDetailsManager(User.withUsername("admin").password("{noop}1234").authorities("ROLE_ANONYMOUS").build());
    }

    @Bean
    PermissionService permissionService(){
        return new PermissionService() {
            @Override
            public Set<String> findRolesByPermission(String permissionCode) {
                return Collections.singleton("ROLE_ANONYMOUS");
            }
        };
    }


}
